package acs.bridge.utility;

import acs.bridge.jreport.JReportItem;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

import java.io.*;
import java.util.Collection;
import java.util.Iterator;

/**
 * acs.utility
 * User: KuznetsovStV
 * Date: 25.12.11
 * Time: 13:36
 */
public class UtilityArcZip implements UtilityArcInterface {

    static final int cBuffer = 2048;
    static final String ext = ".zip";

    /* private String fileName;

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }*/

    public String getExtension() {
        return ext;
    }

    public byte[] arcInputStream(Collection<JReportItem> jReportItemCollection) throws IOException {

        ByteArrayOutputStream l_OutputStream = new ByteArrayOutputStream();

        Iterator iterator = jReportItemCollection.iterator();

        InputStream l_InputStream = null;

        // InputStream l_InputStream = a_InputStream;
        byte l_data[] = new byte[cBuffer];

        ZipOutputStream l_ZipOutputStream =
                new ZipOutputStream(l_OutputStream);

        while (iterator.hasNext()) {

            JReportItem jReportItem = (JReportItem) iterator.next();
            l_InputStream =
                    new BufferedInputStream(new ByteArrayInputStream(jReportItem.getReportData()),
                            cBuffer);

            l_ZipOutputStream.putNextEntry(new ZipEntry(jReportItem.getReportName()));
            int l_count = 0;
            while ((l_count = l_InputStream.read(l_data, 0, cBuffer)) > 0) {
                l_ZipOutputStream.write(l_data, 0, l_count);
            }
        }
        l_ZipOutputStream.closeEntry();
        if (l_InputStream != null)
            l_InputStream.close();
        l_ZipOutputStream.close();

        return l_OutputStream.toByteArray();


    }
}
